#include "thumbnailswidget.h"

#include <QVBoxLayout>
#include <QGraphicsScene>
#include <QGraphicsTextItem>
#include <QTime>
#include <KButtonGroup>
#include <KPushButton>
#include <KMessageBox>
#include <KFileDialog>
#include <QGraphicsPixmapItem>
#include <QLabel>
#include <QStringList>
#include <QGridLayout>

#include <kdclib.h>
#include <KLocale>
#include <KPluginInfo>
#include <interfaces/kdcjobsinterface.h>
extern KDCJobsInterface *gKDCJobsInterface;
#include <interfaces/kdcframegeneratorinterface.h>
extern KDCFrameGeneratorInterface *gKDCFrameGenerator;

#define H_MARGIN 5
#define V_MARGIN 5
#define V_OFFSET 100

ThumbnailsWidget::ThumbnailsWidget( KDCMovie *aMovie, QWidget *aParent ) : QWidget( aParent ), pMovie( aMovie ), pItemCount( 0 )
{
	KButtonGroup *options = new KButtonGroup( this );
	options->setTitle( i18n("Options") );
	
	QVBoxLayout *vLayout = new QVBoxLayout( options );
	QHBoxLayout *hLayout = new QHBoxLayout;
	pNumRadio = new QRadioButton( i18n("Set number of thumbnails"), this );
	pNumRadio->setChecked( true );
	pNumThumbs = new KIntNumInput( this );
	pNumThumbs->setRange( 2, 30 );
	hLayout->addWidget( pNumRadio );
	hLayout->addWidget( pNumThumbs );
	vLayout->addLayout( hLayout );
	pTimeRadio = new QRadioButton( i18n("Set new thumbnail every ( sec )"), this );
	pTimeThumb = new KIntNumInput( this );
	pTimeThumb->setRange( 1, 1000 );
	hLayout = new QHBoxLayout;
	hLayout->addWidget( pTimeRadio );
	hLayout->addWidget( pTimeThumb );
	vLayout->addLayout( hLayout );
	
	QGridLayout *gLayout = new QGridLayout;
	gLayout->addWidget( new QLabel( i18n("Decoration:") ), 0, 0 );
	pDecorationCombo =  new FrameComboBox( this );
	if ( gKDCFrameGenerator )
	{
		QList<KPluginInfo> plugins = gKDCFrameGenerator->pluginList();
		pDecorationCombo->setPlugins( plugins );
		for ( int i=0; i<pDecorationCombo->count(); ++i )
		    pDecorationCombo->setItemIcon( i, gKDCFrameGenerator->preview( plugins.at( i ).name() ) );
	}
	gLayout->addWidget( pDecorationCombo, 0, 1 );
	gLayout->addWidget( new QLabel( i18n("Scheme:") ), 1, 0 );
	pSchemeCombo =  new KComboBox( this );
	pSchemeCombo->addItem( "3x", 3 );
	pSchemeCombo->addItem( "4x", 4 );
	pSchemeCombo->addItem( "5x", 5 );
	pSchemeCombo->addItem( "6x", 6 );
	gLayout->addWidget( pSchemeCombo, 1, 1 );
	vLayout->addLayout( gLayout );
	
	pProgress = new QProgressBar( this );
	vLayout->addWidget( pProgress );
	vLayout->addStretch();
	
	hLayout = new QHBoxLayout;
	hLayout->addStretch();
	KPushButton *btn = new KPushButton( KIcon("view-refresh"), i18n("Generate"), this );
	connect( btn, SIGNAL( clicked() ), this, SLOT( generate() ) );
	hLayout->addWidget( btn );
	btn = new KPushButton( KIcon("process-stop"), i18n("Abort"), this );
	connect( btn, SIGNAL( clicked() ), this, SLOT( abort() ) );
	hLayout->addWidget( btn );
	btn = new KPushButton( KIcon("document-save"), i18n("Save"), this );
	connect( btn, SIGNAL( clicked() ), this, SLOT( save() ) );
	hLayout->addWidget( btn );
	vLayout->addLayout( hLayout );
	
	QHBoxLayout *mainLayout = new QHBoxLayout( this );
	mainLayout->addWidget( options );
	pView = new QGraphicsView( this );
	pView->setScene( new QGraphicsScene( this ) );
	mainLayout->addWidget( pView, 2 );
}

ThumbnailsWidget::~ThumbnailsWidget()
{

}

void ThumbnailsWidget::prepareScene( int aThumbCount, int aPicWidth, int aPicHeight )
{
	QString header;
	header.append( "<table>" );
	header.append( "<tr align=""left"">" );
    header.append( "<td>%1</td>" );
    header.append( "<td>%2</td>" );
	header.append( "</tr>" );
	header.append( "<tr align=""left"">" );
    header.append( "<td>%3</td>" );
    header.append( "<td>%4</td>" );
	header.append( "</tr>" );
	header.append( "<tr align=""left"">" );
    header.append( "<td>%5</td>" );
    header.append( "<td>%6</td>" );
	header.append( "</tr>" );
	header.append( "<tr align=""left"">" );
    header.append( "<td>%7</td>" );
    header.append( "<td>%8</td>" );
	header.append( "</tr>" );
	header.append( "</table>" );

	QGraphicsTextItem *textItem = new QGraphicsTextItem;
	textItem->setDefaultTextColor( Qt::black );
	pView->scene()->addItem( textItem );
	QString movieSize( "%1 ( %2 %3 )" );
	QString size( "%1x%2 @ %3 fps" );
	textItem->setHtml( header.arg( i18n("File:") ).arg( fileName( pMovie->metaData()->name() ) ).arg( i18n("Size:") ).arg( size.arg( pMovie->metaData()->videoMetaData()->width() ).arg( pMovie->metaData()->videoMetaData()->height() ).arg( pMovie->metaData()->videoMetaData()->fps() ) ).arg( i18n("Movie size:") ).arg( "" ).arg( i18n("Duration:") ).arg( QTime().addSecs( pMovie->length() ).toString( "hh:mm:ss" ) ) );
	textItem->setPos( 20, 10 );
	
	
	int row_count = aThumbCount / thumbsPerRow();
	pView->scene()->setSceneRect( 0, 0, H_MARGIN*(thumbsPerRow()+1) + aPicWidth*thumbsPerRow(), V_OFFSET + V_MARGIN*( row_count - 1 ) + row_count*aPicHeight + 10 );
}

int ThumbnailsWidget::thumbsPerRow() const
{
	return pSchemeCombo->itemData( pSchemeCombo->currentIndex() ).toInt();
}

void ThumbnailsWidget::generate()
{
	clear();
	int thumbCount = pNumThumbs->value();
	if ( pTimeRadio->isChecked() )
		thumbCount = qRound( pMovie->length() / pTimeThumb->value() );
	//prepareScene( thumbCount );
	int delta = qRound( pMovie->length()/( thumbCount + 1 ) );
	pProgress->setValue( 0 );
	pProgress->setMaximum( thumbCount );
	int pos;
	for ( int i=0; i<thumbCount; ++i )
	{
		pos = delta*( i+1 );
		pThumbJobs.append( qMakePair( pos, gKDCJobsInterface->thumbnailJob( movieNameFromPos( pMovie, pos ), moviePos( pMovie, pos ) ) ) );
		connect( pThumbJobs.last().second, SIGNAL( result( KJob * ) ), this, SLOT( slotResult( KJob * ) ) );
	}
	pThumbJobs.first().second->start();
}

void ThumbnailsWidget::save()
{
	KFileDialog dlg( KUrl(""), i18n(""), this );
	dlg.setOperationMode( KFileDialog::Saving );
	dlg.setMode( KFile::File );
	dlg.setFilter( "*.bmp|Windows Bitmap\n*.jpg|Joint Photographic Experts Group\n*.png|Portable Network Graphics\n*.tiff|Tagged Image File Format" );
	if ( dlg.exec() )
	{
		QImage img( pView->scene()->width(), pView->scene()->height(), QImage::Format_RGB32 );
		QPainter painter( &img );
		pView->scene()->setBackgroundBrush( Qt::white );
		pView->scene()->render( &painter );
		if ( !img.save( "/home/marcin/aaaa.jpg", "jpg" ) )
			KMessageBox::error( this, i18n("There was an error during process.") );
	}
}

void ThumbnailsWidget::abort()
{
	clear();
	clear();
	KMessageBox::information( this, i18n("Proces was aborded.") );
}

void ThumbnailsWidget::slotResult( KJob *aJob )
{
	if ( aJob->error() )
	{
		KMessageBox::error( this, i18n("<b>There was an error during prosess:</b>\n%1").arg( aJob->errorString() ) );
		clear();
	}
	else
	{
		QPair<int,KDCFrameJobInterface*> obj = pThumbJobs.takeFirst();
		QString error;
		QPixmap pix = obj.second->resultFrame();
		pix = gKDCFrameGenerator->createFrame( pDecorationCombo->currentText(), pix, 0, 0, error );
		if ( pProgress->value() == 0 )
			prepareScene( pThumbJobs.size() + 1, pix.width(), pix.height() );
		addThumbs( obj.first, pix );
		pProgress->setValue( pProgress->value() + 1 );
		if ( !pThumbJobs.isEmpty() )
			pThumbJobs.first().second->start();
	}
}

void ThumbnailsWidget::clear()
{
	pItemCount = 0;
	pView->scene()->clear();
	while ( !pThumbJobs.isEmpty() )
		pThumbJobs.takeFirst().second->deleteLater();
	pThumbJobs.clear();
}

void ThumbnailsWidget::addThumbs( int aPos, const QPixmap &aPic )
{
	QGraphicsPixmapItem *pixItem = pView->scene()->addPixmap( aPic );
	QGraphicsTextItem *textItem = new QGraphicsTextItem( pixItem );
	textItem->setDefaultTextColor( Qt::white );
	textItem->setHtml( QString( "<b>%1</b>" ).arg( QTime().addSecs( aPos ).toString( "hh:mm:ss" ) ) );
	textItem->setPos( 10, aPic.height() - 40 );
	textItem->setZValue( 1 );
	
	int row = pItemCount / thumbsPerRow();
	int row_count = pItemCount % thumbsPerRow();
	int x = H_MARGIN + row_count*aPic.width() + ( ( row_count != 0 ) ? qRound( H_MARGIN*row_count ) : 0 );
	int y = V_OFFSET + row*aPic.height() + ( ( row > 0 ) ? qRound( V_MARGIN*row ) : 0 );
	pixItem->setPos( x, y );
	pixItem->setZValue( 1 );
	++pItemCount;
}
